var express = require("express")
var router = express.Router()
var QcloudSms = require("qcloudsms_js")
var connection = require("../../../db/sql")
var jwt = require("jsonwebtoken")
var My = require("./mysql")
var upload = require("./upload.js")
var shopupload = require("./shopupload.js")
const bcrypt = require("bcryptjs")
const fs = require("fs")
const request = require("request")
const path = require("path")
var multiparty = require("multiparty")
const multer = require("multer")
const { log } = require("console")
var multipart = require("connect-multiparty")
const { json } = require("body-parser")
var multipartMiddleware = multipart()

/* 个人资料修改*/
router.post("/api/my/personaldata", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  let myMesg = req.body
  JSON.stringify(Object.assign(myMesg, tokenObj))
  console.log(myMesg)
  connection.query(My.updateMyMsg(myMesg), function (err, resluts) {
    if (err) {
      res.send({
        status: 405,
        msg: "出错",
        err,
      })
    } else {
      connection.query(My.selectMy(myMesg), function (err, reslut) {
        delete reslut[0].user_id
        delete reslut[0].user_phone
        delete reslut[0].user_password
        res.send({
          status: 200,
          msg: "个人资料更新成功",
          data: reslut,
        })
      })
    }
  })
})

/*上传商品*/
router.post("/api/my/uploadshops", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  let params = req.body
  console.log(params)
  connection.query(My.getPickerId(params.value), function (err, reslut) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询id出错",
        err,
      })
    }
    let id = { shopId: reslut[0].topic_id }
    Object.assign(params, id, tokenObj)
    console.log(params)

    connection.query(My.insertShops(params), function (errs, resluts) {
      if (errs) {
        res.send({
          code: 202,
          msg: "插入失败",
          errs,
        })
      }

      res.send({
        code: 200,
        msg: "插入成功",
        data: resluts,
      })
    })
  })
})

/*获取人脸识别token*/
router.get("/api/my/userface", function (req, res, next) {
  async function main() {
    var options = {
      method: "POST",
      url: "https://aip.baidubce.com/oauth/2.0/token?client_id=XGBj8g4Z7rZoOV58zxoUci7e&client_secret=5SbAvkGN9NMyQG6FVBfAjbVzGikAH8C4&grant_type=client_credentials",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }

    request(options, function (error, response) {
      if (error) throw new Error(error)
      console.log(response.body)
      res.send({
        code: 200,
        msg: "生成token成功",
        data: response.body,
      })
    })
  }

  main()
})

/*注册人脸*/
router.post("/api/my/registeruserface", function (req, res, next) {
  let baseDatas = req.body
  const request = require("request")
  let token = req.headers.token
  let tokenObj = jwt.decode(token)

  async function main() {
    var options = {
      method: "POST",
      url: `https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=${baseDatas.access_token}`,
      headers: {
        "Content-Type": "application/json",
      },
      // image 可以通过 getFileContentAsBase64("C:\fakepath\u=171957948,2217760987&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto.webp") 方法获取,
      body: JSON.stringify({
        group_id: "user",
        image: `${baseDatas.baseData}`,
        image_type: "BASE64",
        user_id: `${tokenObj.tel}`,
      }),
    }

    request(options, function (error, response) {
      if (error) throw new Error(error)
      console.log(response.body)
      res.send({
        code: 200,
        msg: "人脸注册成功",
        data: response.body,
      })
    })
  }

  /**
   * 获取文件base64编码
   * @param string  path 文件路径
   * @return string base64编码信息，不带文件头
   */
  function getFileContentAsBase64(path) {
    const fs = require("fs")
    try {
      return fs.readFileSync(path, { encoding: "base64" })
    } catch (err) {
      throw new Error(err)
    }
  }
  main()
})

/*人脸登录*/
router.post(
  "/api/my/userfacelogin",

  async function (req, res, next) {
    // let file = req.files[0].path
    // console.log(file)
    // // 将图片转换为Base64格式
    // function parse(file) {
    //   let filePath = path.resolve(file) // 原始文件地址
    //   // let fileName = filePath.split('\\').slice(-1)[0].split('.'); // 提取文件名
    //   // let fileMimeType = mimeType.lookup(filePath); // 获取文件的 memeType

    //   // 如果不是图片文件，则退出
    //   // if (!fileMimeType.toString().includes('image')) {
    //   //     console.log(chalk.red(`Failed! ${filePath}:\tNot image file!`));
    //   //     return;
    //   // }

    //   // 读取文件数据
    //   let data = fs.readFileSync(filePath)
    //   data = Buffer.from(data).toString("base64")

    //   // // 转换为 data:image/jpeg;base64,***** 格式的字符串
    //   // let base64 = 'data:' + fileMimeType + ';base64,' + data;
    //   //
    //   // // 创建输出目录
    //   // let outPath = path.resolve('./base64/');
    //   // let outFileName = `${fileName.join('-')}.txt`;
    //   // let outFile = path.join(outPath, outFileName);
    //   // if (fs.existsSync(outPath)) {
    //   //     saveData(base64, outFile, filePath, outFileName);
    //   // } else {
    //   //     mkdirp(outPath, () => {
    //   //         saveData(base64, outFile, filePath, outFileName);
    //   //     });
    //   // }
    //   return data
    // }

    // let base64 = parse(file)
    // console.log(base64)
    let base64 = req.body.value
    console.log(base64)
    // 获取access_token
    var options = {
      method: "POST",
      url: "https://aip.baidubce.com/oauth/2.0/token?client_id=XGBj8g4Z7rZoOV58zxoUci7e&client_secret=5SbAvkGN9NMyQG6FVBfAjbVzGikAH8C4&grant_type=client_credentials",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }

    request(options, function (error, response) {
      if (error) throw new Error(error)
      console.log(response.body)
      let access_token = JSON.parse(response.body).access_token
      console.log(access_token)
      // 人脸对比
      const request = require("request")

      async function main() {
        var options = {
          method: "POST",
          url: `https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=${access_token}`,
          headers: {
            "Content-Type": "application/json",
          },
          // image 可以通过 getFileContentAsBase64("C:\fakepath\u=923655713,3111985973&fm=253&app=138&size=w931&n=0&f=JPG&fmt=auto.webp") 方法获取,
          body: JSON.stringify({
            group_id_list: "user",
            image: JSON.stringify(base64),
            image_type: "BASE64",
          }),
        }

        request(options, function (error1, response1) {
          if (error1) throw new Error(error1)
          console.log(response1.body)
          res.send({
            code: 200,
            data: response1.body,
          })
        })
      }

      /**
       * 获取文件base64编码
       * @param string  path 文件路径
       * @return string base64编码信息，不带文件头
       */
      function getFileContentAsBase64(path) {
        const fs = require("fs")
        try {
          return fs.readFileSync(path, { encoding: "base64" })
        } catch (err) {
          throw new Error(err)
        }
      }

      main()
    })
  }
)

/*上传图片到oss接口*/
router.post(
  "/api/my/upload",
  multer({
    //设置文件存储路径
    dest: "public/image",
  }).array("file", 1),
  upload.upload
)

// /*商品图片上传接口*/
// router.post(
//   "/api/my/uploadpics",
//   multer({
//     //设置文件存储路径
//     dest: "public/images",
//   }).array("file"),
//   shopupload.uploadPics
// )

/*商品图片上传接口1.0*/
router.post("/api/my/uploadshopsmsg", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  const { imgs } = req.body
  let imgsArr = JSON.parse(imgs)
  let parm = req.body
  let params = parm.obj
  console.log("=====")
  // console.log(parm[obj])
  console.log(params)
  console.log(imgsArr)
  connection.query(My.getPickerId(params.value), function (err, reslut) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询id出错",
        err,
      })
    }
    let id = { shopId: reslut[0].topic_id }
    Object.assign(params, id, tokenObj)
    console.log(params)

    connection.query(My.insertShops(params), function (errs, resluts) {
      if (errs) {
        res.send({
          code: 202,
          msg: "插入失败",
          errs,
        })
      }

      // 将图片插入src中
      // 找id
      connection.query(My.selectShopUpload(params.des), function (e, id) {
        if (e) {
          res.send({
            code: 301,
            msg: "查找id失败",
            e,
          })
        }

        let shopId = id[0].good_id
        console.log(shopId)
        imgsArr.map((item) => {
          connection.query(My.insertListSrc(item, shopId), function (er, re) {
            if (er) {
              res.send({
                code: 302,
                msg: "插入图片失败",
                er,
              })
            }
          })
        })

        res.send({
          code: 200,
          msg: "插入成功",
        })
      })
    })
  })
})

/*个人头像修改*/
router.post("/api/my/headImgData", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  let myMesg = req.body
  JSON.stringify(Object.assign(myMesg, tokenObj))
  console.log(myMesg)
  connection.query(My.updateMyHead(myMesg), function (err, resluts) {
    if (err) {
      res.send({
        status: 405,
        msg: "出错",
        err,
      })
    } else {
      connection.query(My.selectMy(myMesg), function (err, reslut) {
        delete reslut[0].user_id
        delete reslut[0].user_phone
        delete reslut[0].user_password
        res.send({
          status: 200,
          msg: "头像更新成功",
          data: reslut,
        })
      })
    }
  })
})

/*获取picker值*/
router.get("/api/my/getpicker", function (req, res, next) {
  connection.query(My.getPicker(), function (err, resluts) {
    if (err) {
      res.send({
        msg: "查询错误",
        data: err,
      })
    }
    res.send({
      status: 200,
      msg: "查询成功",
      data: resluts,
    })
  })
})

// 校园认证模块
router.post("/api/my/userattestation", function (req, res, next) {
  let data = req.body
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  console.log(data)
  connection.query(My.isCheckPersion(data), function (err, resluts) {
    if (err) {
      res.send({
        msg: "查询错误",
        data: err,
      })
    } else if (resluts.length === 0) {
      res.send({
        status: 201,
        msg: "暂无该生信息，请联系管理员",
      })
    } else {
      // 修改信息
      connection.query(My.updateUserInfo(tokenObj), function (err, reslut) {
        if (err) {
          res.send({
            msg: "修改失败",
            data: err,
          })
        }
        res.send({
          status: 200,
          msg: "认证成功",
          data: reslut,
        })
      })
    }
  })
})

// 校验是否校园认证
router.get("/api/my/ischeckuser", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  connection.query(My.isCheckSuccess(tokenObj), function (err, resluts) {
    if (err) {
      res.send({
        code: 201,
        msg: "出错了",
        err,
      })
    }

    res.send({
      code: 200,
      msg: "认证成功",
      data: resluts,
    })
  })
})

/*获取地址列表*/
router.get("/api/my/addresslist", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  connection.query(My.getAddressList(tokenObj), function (err, resluts) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询出错",
        data: err,
      })
    }

    res.send({
      code: 200,
      msg: "查询用户地址列表成功",
      data: resluts,
    })
  })
})

/*增加用户地址*/
router.post("/api/my/useraddaddress", function (req, res, next) {
  let obj = req.body
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  connection.query(My.getUserId(tokenObj), function (err, reslut) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询用户id出错",
        data: err,
      })
    }

    let userId = { user_id: reslut[0].user_id }
    // 将所有的数据封装成插入的对象
    let address = obj.province + obj.city + obj.county + obj.addressDetail
    let obj1 = { address }
    Object.assign(obj, obj1, userId)
    console.log(obj)
    // 如果传过来的是默认地址
    if (obj.isDefault) {
      connection.query(
        My.selectDefaultAddress(userId.user_id),
        function (error, reslutsisDefault) {
          if (error) {
            res.send({
              code: 203,
              msg: "查询默认id出错",
              data: err,
            })
          }
          let isDefaultAddressId = reslutsisDefault[0].address_id
          console.log(isDefaultAddressId)
          connection.query(
            My.updateDefaultAddress(isDefaultAddressId),
            function (err1, reslutsUpdate) {
              if (err1) {
                res.send({
                  code: 204,
                  msg: "更新默认地址失败",
                  data: err1,
                })
              }
            }
          )
        }
      )
    }

    connection.query(My.addUserAddress(obj), function (errs, resluts) {
      if (errs) {
        res.send({
          code: 202,
          msg: "添加地址失败",
          data1: errs,
        })
      }

      res.send({
        code: 200,
        msg: "添加地址成功",
        data2: resluts,
      })
    })
  })
  // console.log(data)
})

/*用户反馈*/
router.post("/api/my/feedback", multipartMiddleware, function (req, res, next) {
  console.log(req.body)
  let param = req.body
  connection.query(My.insertFeedback(param), function (err, reslut) {
    if (err) {
      res.send({
        code: 201,
        msg: "插入失败",
        err,
      })
    }

    connection.query(My.selectFeedbackId(param), function (errs, resId) {
      if (errs) {
        res.send({
          code: 202,
          msg: "查找id失败",
          errs,
        })
      }
      let id = resId[0].feedback_id
      console.log(id)
      // 向src数据库查图片
      let imgArr = JSON.parse(param.imgs)
      console.log(imgArr)
      imgArr.map((item) => {
        connection.query(
          My.insertFeedbackSrc(item, id),
          function (error, resluts) {
            if (error) {
              res.send({
                code: 203,
                msg: "插入图片失败",
                error,
              })
            }
          }
        )
      })

      res.send({
        code: 200,
        msg: "提交成功",
      })
    })
  })
})

/*获取在线商品*/
router.get("/api/my/getonlineshop", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  connection.query(My.selectOnlineData(tokenObj.tel), function (err, resluts) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询失败",
        err,
      })
    }

    res.send({
      code: 200,
      msg: "查询成功",
      data: resluts,
    })
  })
})

/*下架商品*/
router.post("/api/my/offself", function (req, res, next) {
  let id = req.body.id
  console.log(id)
  try {
    connection.query(My.delForeignKey(id), function (err, reslut) {
      if (err) {
        res.send({
          code: 201,
          msg: "删除外键出错",
          err,
        })
      }

      connection.query(My.delKey(id), function (errs, resluts) {
        if (errs) {
          res.send({
            code: 202,
            msg: "商品有关联,下架失败",
            errs,
          })
        } else {
          res.send({
            code: 200,
            msg: "商品下架成功",
          })
        }
      })
    })
  } catch (e) {
    console.log(e)
  }
})

/*获取审核token*/
router.get("/api/my/getexaminetoken", function (req, res, next) {
  const request = require("request")

  async function main() {
    var options = {
      method: "POST",
      url: "https://aip.baidubce.com/oauth/2.0/token?client_id=CV6eGlFk1sPnSiH079gLEn25&client_secret=MphTVLGazG7m7wAxbTZrTkrDvOFggCdi&grant_type=client_credentials",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }

    request(options, function (error, response) {
      if (error) throw new Error(error)
      console.log(response.body)
      res.send({
        code: 200,
        data: response.body,
      })
    })
  }

  main()
})

/*图片审核*/

router.post("/api/my/examinepic", function (req, res, next) {
  let obj = req.body
  console.log(obj)
  let resluts = []
  const request = require("request")
  let option = {
    method: "POST",
    url: `https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=${obj.token}`,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    form: {
      imgUrl: "",
    },
  }
  async function main() {
    let options = option
    request(options, function (error, response) {
      if (error) throw new Error(error)
      // console.log(response.body)
      resluts.push(response.body)
      if (resluts.length == obj.imgArr.length) {
        console.log(resluts)
        res.send({
          code: 200,
          msg: "图片审核结果",
          data: resluts,
        })
      }
    })
  }

  obj.imgArr.forEach((item, index) => {
    option.form.imgUrl = item
    main()
  })
})

/*文字审核*/
router.post("/api/my/examineword", function (req, res, next) {
  let obj = req.body
  let resluts = []
  console.log(obj)
  let option = {
    method: "POST",
    url: `https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=${obj.token}`,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    form: {
      text: "",
    },
  }

  async function main() {
    let options = option
    request(options, function (error, response) {
      if (error) throw new Error(error)
      // console.log(response.body)
      resluts.push(response.body)
      if (resluts.length == obj.wordobj.length) {
        console.log(resluts)
        res.send({
          code: 200,
          msg: "文字审核结果",
          data: resluts,
        })
      }
    })
  }

  // main()
  obj.wordobj.forEach((item, index) => {
    option.form.text = item
    main()
  })
})

/*是否认证*/
router.get("/api/my/examincheck", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  connection.query(My.selectAtten(tokenObj), function (err, reslut) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询失败",
        err,
      })
    }

    res.send({
      code: 200,
      msg: "查询成功",
      data: reslut,
    })
  })
})

/*获取订单数量*/
router.get("/api/my/getordernum", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  // 查询用户id
  connection.query(My.selectUserId(tokenObj), function (err, reslut) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询失败",
        err,
      })
    }

    let id = reslut[0].user_id
    connection.query(
      My.selectOrderNum(id),

      function (errs, resluts) {
        if (errs) {
          res.send({
            code: 202,
            msg: "查询失败",
            errs,
          })
        }
        connection.query(My.selectOrderPayNum(id), function (e, r) {
          res.send({
            code: 200,
            msg: "查询成功",
            data: {
              resluts,
              r,
            },
          })
        })
      }
    )
  })
  // connection.query(My.selectAtten(tokenObj), function (err, reslut) {
  //   if (err) {
  //     res.send({
  //       code: 201,
  //       msg: "查询失败",
  //       err,
  //     })
  //   }

  //   res.send({
  //     code: 200,
  //     msg: "查询成功",
  //     data: reslut,
  //   })
  // })
})

module.exports = router
